package com.pengtu.integration.email;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * MIME邮件服务类.
 * 
 * 演示由Freemarker引擎生成的的html格式邮件, 并带有附件.
 * 
 * @author calvin
 */
public class MimeMailService {

	private static final String DEFAULT_ENCODING = "utf-8";

	private static Logger logger = LoggerFactory.getLogger(MimeMailService.class);
    private String from;
	private JavaMailSender mailSender;
	private Configuration freemarkerConfiguration;

	/**
	 * Spring的MailSender.
	 */
	public void setMailSender(JavaMailSender mailSender) {
		this.mailSender = mailSender;
	}
	
	public void setFrom(String from) {
		this.from = from;
	}

	/**
	 * 注入Freemarker引擎配置,构造Freemarker 邮件内容模板.
	 */
	public void setFreemarkerConfiguration(Configuration freemarkerConfiguration) throws IOException {
		//根据freemarkerConfiguration的templateLoaderPath载入文件.
		this.freemarkerConfiguration = freemarkerConfiguration;
	}

	/**
	 * 发送MIME格式的用户修改通知邮件.
	 */
	public void sendNotificationMail(String email,String Name,String userName,String password) {
		try {
			MimeMessage msg = mailSender.createMimeMessage();
			MimeMessageHelper helper = new MimeMessageHelper(msg, true, DEFAULT_ENCODING);
			helper.setTo(email);
			helper.setFrom(from);
			helper.setSubject("用户修改通知");
			String content = generatePasswordContent(Name,userName,password);
			helper.setText(content, true);
			mailSender.send(msg);
			logger.info("用户信息修改邮件已发送至"+email);
		} catch (MessagingException e) {
			logger.error("构造邮件失败", e);
		} catch (Exception e) {
			logger.error("发送邮件失败", e);
		}
	}
	
	
	/**
	 * 发送MIME格式的用户注册信息通知邮件.
	 */
	public void sendRegisteredMail(String email,String Name,String userName,String password) {
		try {
			MimeMessage msg = mailSender.createMimeMessage();
			MimeMessageHelper helper = new MimeMessageHelper(msg, true, DEFAULT_ENCODING);
			helper.setTo(email);
			helper.setFrom(from);
			helper.setSubject("用户注册成功通知");
			String content = generateRegisteredContent(Name,userName,password);
			helper.setText(content, true);
			mailSender.send(msg);
			logger.info("用户注册邮件已发送至"+email);
		} catch (MessagingException e) {
			logger.error("构造邮件失败", e);
		} catch (Exception e) {
			logger.error("发送邮件失败", e);
		}
	}

	/**
	 * 使用Freemarker生成html格式内容.
	 */

	private String generateRegisteredContent(String name,String userName,String password) throws MessagingException {
		try {
			Map<String, String> context = new HashMap<String, String>();
			context.put("userName", userName);
			context.put("name", name);
			context.put("password", password);
			Template template = freemarkerConfiguration.getTemplate("registered.ftl", DEFAULT_ENCODING);
			return FreeMarkerTemplateUtils.processTemplateIntoString(template, context);
		} catch (IOException e) {
			logger.error("生成邮件内容失败, FreeMarker模板不存在", e);
			throw new MessagingException("FreeMarker模板不存在", e);
		} catch (TemplateException e) {
			logger.error("生成邮件内容失败, FreeMarker处理失败", e);
			throw new MessagingException("FreeMarker处理失败", e);
		}
	}

	/**
	 * 使用Freemarker生成html格式内容.
	 */

	private String generatePasswordContent(String name,String userName,String password) throws MessagingException {
		try {
			Map<String, String> context = new HashMap<String, String>();
			context.put("userName", userName);
			context.put("name", name);
			context.put("password", password);
			Template template = freemarkerConfiguration.getTemplate("password.ftl", DEFAULT_ENCODING);
			return FreeMarkerTemplateUtils.processTemplateIntoString(template, context);
		} catch (IOException e) {
			logger.error("生成邮件内容失败, FreeMarker模板不存在", e);
			throw new MessagingException("FreeMarker模板不存在", e);
		} catch (TemplateException e) {
			logger.error("生成邮件内容失败, FreeMarker处理失败", e);
			throw new MessagingException("FreeMarker处理失败", e);
		}
	}
	/**
	 * 获取classpath中的附件.
	 */
	public File generateAttachment() throws MessagingException {
		try {
			Resource resource = new ClassPathResource("/email/mailAttachment.txt");
			return resource.getFile();
		} catch (IOException e) {
			logger.error("构造邮件失败,附件文件不存在", e);
			throw new MessagingException("附件文件不存在", e);
		}
	}
}
